package com.bm.util;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import com.mysql.jdbc.StringUtils;


public class RedisUtil {
	   private static Logger logger=LogManager.getLogger(RedisUtil.class);
	     
	    private static JedisPool jedisPool = null;
	     
	    /**
	     * redis过期时间,以秒为单位
	     */
	    public final static int EXRP_HOUR = 60*60;          //一小时
	    public final static int EXRP_DAY = 60*60*24;        //一天
	    public final static int EXRP_MONTH = 60*60*24*30;   //一个月
	     
	    /**
	     * 初始化Redis连接池
	     */
	    private static void initialPool(){
	        try {
	        	Config config=Config.getConfig();
	            JedisPoolConfig jedisconfig = new JedisPoolConfig();
	            jedisconfig.setMaxActive(config.getMaxActive());
	            jedisconfig.setMaxIdle(config.getMinIdle());
	            jedisconfig.setMaxWait(config.getRedisMaxWait());
	            // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；（效率和准确性的选择？？）
	            jedisconfig.setTestOnBorrow(false);
	            jedisPool = new JedisPool(jedisconfig, config.getRedisHost(), config.getRedisPort(), config.getRedisTimeOut());
	        } catch (Exception e) {
	           e.printStackTrace();
	        }
	    }
	     
	     
	    /**
	     * 在多线程环境同步初始化
	     */
	    private static synchronized void poolInit() {
	        if (jedisPool == null) {  
	            initialPool();
	        }
	    }
	 
	     
	    /**
	     * 同步获取Jedis实例
	     * @return Jedis
	     */
	    public synchronized static Jedis getJedis() {  
	        if (jedisPool == null) {  
	            poolInit();
	        }
	        Jedis jedis = null;
	        try {  
	            if (jedisPool != null) {  
	                jedis = jedisPool.getResource(); 
	            }
	        } catch (Exception e) {  
	        	logger.warn("【open jedisconnection error】"+e.toString());
	        }
	        return jedis;
	    }  
	     
	     
	    /**
	     * 释放jedis资源
	     * @param jedis
	     */
	    public static void returnResource(final Jedis jedis) {
	        if (jedis != null && jedisPool !=null) {
	            try {
					jedisPool.returnResource(jedis);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.warn("【close jedisconnection error】"+e.toString());
				}
	        }
	    }
	     
	     
	    /**
	     * 设置 String
	     * @param key
	     * @param value
	     */
	    public static void setString(String key ,String value){
	        try {
	            value = StringUtils.isNullOrEmpty(value) ? "" : value;
	            getJedis().set(key,value);
	        } catch (Exception e) {
	        }
	    }
	     
	    /**
	     * 设置 过期时间
	     * @param key
	     * @param seconds 以秒为单位
	     * @param value
	     */
	    public static void setString(String key ,int seconds,String value){
	        try {
	            value = StringUtils.isNullOrEmpty(value)  ? "" : value;
	            getJedis().setex(key, seconds, value);
	        } catch (Exception e) {
	        }
	    }
	     
	    /**
	     * 获取String值
	     * @param key
	     * @return value
	     */
	    public static String getString(String key){
	        if(getJedis() == null || !getJedis().exists(key)){
	            return null;
	        }
	        return getJedis().get(key);
	    }
}
